﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Windows.Forms;
using System.Threading;
using System.Security.Cryptography;
using System.Net;
using System.IO;

namespace TNCAddIn
{
    partial class TNCFormRegion
    {
        #region 窗体区域工厂

        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Appointment)]
        [Microsoft.Office.Tools.Outlook.FormRegionName("TNCAddIn.TNCFormRegion")]
        public partial class TNCFormRegionFactory
        {
            // 在初始化窗体区域之前发生。
            // 若要阻止窗体区域出现，请将 e.Cancel 设置为 True。
            // 使用 e.OutlookItem 获取对当前 Outlook 项的引用。
            private void TNCFormRegionFactory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
            {
            }
        }

        #endregion

        // 在显示窗体区域之前发生。
        // 使用 this.OutlookItem 获取对当前 Outlook 项的引用。
        // 使用 this.OutlookFormRegion 获取对窗体区域的引用。
        private void TNCFormRegion_FormRegionShowing(object sender, System.EventArgs e)
        {
            Outlook.AppointmentItem item = (Outlook.AppointmentItem)this.OutlookItem;
            item.Write += new Outlook.ItemEvents_10_WriteEventHandler(Item_Save);
            //item.BeforeDelete += new Outlook.ItemEvents_10_BeforeDeleteEventHandler(Item_Delete);
            
            if (item.UserProperties["sync"] == null)
                item.UserProperties.Add("sync", Outlook.OlUserPropertyType.olText);
            item.UserProperties["sync"].Value = "yes";
            //item.Save();
            modified = false;
            this.centerComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            updateCenters();
        }

        private Boolean modified;

        //约会被修改，设置为未同步
        private void Item_Save(ref bool Cancel)
        {
            //MessageBox.Show("save");
            modified = true;
        }

        //约会被删除，加到删除列表
        private void Item_Delete(object it, ref bool Cancel)
        {
            try
            {
                lock (Properties.Settings.Default.List)
                {
                    Outlook.AppointmentItem item = (Outlook.AppointmentItem)it;
                    if (Properties.Settings.Default.List != "")
                        Properties.Settings.Default.List += ",";
                    Properties.Settings.Default.List += item.GlobalAppointmentID;
                    Properties.Settings.Default.Save();
                }
            } catch (Exception e) {
                MessageBox.Show(e.Message);
            }
        }

        // 在关闭窗体区域时发生。
        // 使用 this.OutlookItem 获取对当前 Outlook 项的引用。
        // 使用 this.OutlookFormRegion 获取对窗体区域的引用。
        private void TNCFormRegion_FormRegionClosed(object sender, System.EventArgs e)
        {
            if(modified)
            {
                Outlook.AppointmentItem item = (Outlook.AppointmentItem)this.OutlookItem;
                if (item.UserProperties["sync"] == null)
                    item.UserProperties.Add("sync", Outlook.OlUserPropertyType.olText);
                item.UserProperties["sync"].Value = "no";
                item.Save();
            }
        }

        //启用线程更新budget中心
        private void updateBtn_Click(object sender, EventArgs e)
        {
            HttpClient hc = new HttpClient();
            try
            {
                hc.GetBugetCenter();
                updateCenters();
                //MessageBox.Show("更新成功");
            }
            catch (Exception ex)
            {
                //MessageBox.Show("更新失败：" + ex.Message);
            }
        }

        private void updateCenters()
        {
            String[] _centerArray = Properties.Settings.Default.Centers.Split(',');

            this.centerComboBox.Items.Clear();
            this.centerComboBox.Items.AddRange(_centerArray);
            Outlook.AppointmentItem item = (Outlook.AppointmentItem)this.OutlookItem;
            if (item.UserProperties["buget"] != null)
            {
                Boolean found = false;
                String buget = item.UserProperties["buget"].Value;
                int i;
                for (i = 0; i < _centerArray.Length; i++)
                {
                    if (_centerArray[i] == buget)
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                    this.centerComboBox.SelectedIndex = i;
                else
                {
                    this.centerComboBox.Items.Add(buget);
                    this.centerComboBox.SelectedIndex = i;
                }
            }
            else
            {
                String buget = Properties.Settings.Default.DefaultBudgetCenter;
                Boolean found = false;
                int i;
                for (i = 0; i < _centerArray.Length; i++) {
                    if (_centerArray[i] == buget) {
                        found = true;
                        break;
                    }
                }
                if (found)
                    this.centerComboBox.SelectedIndex = i;
                else {
                    this.centerComboBox.Items.Add(buget);
                    this.centerComboBox.SelectedIndex = i;
                }
            }
        }

        private void centerComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Outlook.AppointmentItem item = (Outlook.AppointmentItem)this.OutlookItem;
            if (item.UserProperties["buget"] == null)     
                item.UserProperties.Add("buget", Outlook.OlUserPropertyType.olText);
            item.UserProperties["buget"].Value = this.centerComboBox.SelectedItem.ToString();
            item.Save();
            if (item.UserProperties["buget"].Value == "私人事件")
            {
                if (Properties.Settings.Default.List != "")
                    Properties.Settings.Default.List += ",";
                Properties.Settings.Default.List += item.GlobalAppointmentID;
                Properties.Settings.Default.Save();
            }
            else {
                int s = Properties.Settings.Default.List.IndexOf("私人事件");
                if (s != -1) {
                    int c = Properties.Settings.Default.List.IndexOf(",", s);
                    if (c == -1)
                    {
                        Properties.Settings.Default.List = Properties.Settings.Default.List.Substring(0, s);
                        Properties.Settings.Default.List.TrimEnd(",".ToArray());
                    }
                    else {
                        Properties.Settings.Default.List = Properties.Settings.Default.List.Substring(0, s)
                            + Properties.Settings.Default.List.Substring(c+1);
                    }
                }
            }
        }
    }
}
